// utils/color-thief.js
class ColorThief {
    constructor() {
        this.palette = [];
    }

    createImage(url) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.src = url;
            img.crossOrigin = 'Anonymous';
            img.addEventListener('load', () => resolve(img));
            img.addEventListener('error', (err) => reject(err));
        });
    }

    getColor(image, quality = 10) {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const width = image.width;
        const height = image.height;

        canvas.width = width / quality;
        canvas.height = height / quality;
        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        this.palette = this.getPalette(imageData.data);

        return this.rgbToHex(this.palette[0]);
    }

    getPalette(data) {
        const colorCounts = {};
        const pixelArray = [];

        for (let i = 0; i < data.length; i += 4) {
            const rgb = [data[i], data[i + 1], data[i + 2]];
            pixelArray.push(rgb);
            const hex = this.rgbToHex(rgb);

            if (hex in colorCounts) {
                colorCounts[hex]++;
            } else {
                colorCounts[hex] = 1;
            }
        }

        return Object.keys(colorCounts).sort((a, b) => colorCounts[b] - colorCounts[a])
            .map(hex => this.hexToRgb(hex));
    }

    rgbToHex(rgb) {
        return '#' + ((1 << 24) | (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16).slice(1).toUpperCase();
    }

    hexToRgb(hex) {
        const hexValue = parseInt(hex.slice(1), 16);
        return [(hexValue >> 16) & 255, (hexValue >> 8) & 255, hexValue & 255];
    }
}

module.exports = ColorThief;
